package com.boolib.animate.framework.web;

import com.boolib.animate.commons.utils.CheckUtil;
import com.boolib.animate.framework.service.base.impl.FileInfoService;
import com.boolib.animate.framework.service.extend.IUploadService;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author nier
 * @create 2020-02-20 15:11
 */
@RestController
@RequestMapping("/api/extend")
public class ApiExtendController {

    @Value("${system.uploadpath}")
    private String uploadPath;
    @Autowired
    private IUploadService iUploadService;

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private HttpServletRequest request;


    /**
     * 普通用户上传图片
     * @param file
     * @return
     * @throws IOException
     * @throws FileUploadException
     */

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping("upload")
    public String uploadImage(MultipartFile file) throws FileUploadException {
        try {
            CheckUtil.checkMemberUpload(file);
            return iUploadService.uploadImage(uploadPath, file);
        }catch (IOException | FileUploadException ex){
            throw new FileUploadException(ex.getMessage());
        }
    }


    /**
     * 普通用户上传一组图片
     * @param request
     * @return
     * @throws IOException
     * @throws FileUploadException
     */

    @PostMapping("uploads")
    public List<String> uploadImagesMember(MultipartHttpServletRequest request) throws IOException, FileUploadException {
        try {
            CheckUtil.checkMemberUploads(request);
            return  iUploadService.uploadImages(uploadPath, request.getMultiFileMap().get("files"));
        }catch (IOException | FileUploadException ex){
            throw new FileUploadException(ex.getMessage());
        }
    }



    @DeleteMapping("file")
    public void removeOne(String name){
        iUploadService.removeOne(uploadPath,name);
    }



    @DeleteMapping("/files")
    public void removeMore(){
        List<String> names = Arrays.asList(request.getParameterMap().get("names"));
        iUploadService.removeList(uploadPath,names);
    }

}
